/**
 * @author HuntBao
 * @context Member View
 */
 App.Views.MemberView = Backbone.View.extend({
     
 	 template: tpl.memberItem,
 	 
 	 className: 'member-row',
 	 
 	 events: {
 	 	'click': 'clickRowHandler',
        'click .delete-member': 'deleteMemberHandler',
        'keydown .member-inp': 'keydownHandler',
        'click .add-member-confirm': 'addMemberHandler',
        'click .add-member-cancel': 'cancelAddMemberHandler',
        'click .add-member': 'addMemberToSpecificRole',
        'click .readd-member': 'addMemberToSpecificRole',
        'click .toggle-icon': 'toggleHandler',
        'dblclick': 'toggleHandler'
 	 },
 	 
 	 titles: {
        deleteMemberTitle: App.i18n.get('RemoveMember'),
        addMemberTitle: App.i18n.get('addMember'),
        updateMember: App.i18n.get('updateMember'),
        editMemberInpPH: App.i18n.get('createMemberPlaceholder'),
        addMemberConfirmTitle: App.i18n.get('ok'),
        addMemberCancelTitle: App.i18n.get('cancel')
 	 },
 	 
     initialize : function() {
 		 var self = this;
 		 self.model.on('change:name', self.updateMemberName, self);
     },
     
     render: function(){
        var self = this;
        if(self.model.get('org') && self.model.get('memberCount') > 0){
            self.model.set({hasMember: true}, {silent: true});
        }
        data = self.model.toJSON();
        _.extend(data, self.titles);
        if(data.editable){
            if(data.status === -1){
                //can add
                data.memberStatus = App.i18n.get('add');
                data.memberCanAdd = true;
            }else if(data.status === 0){
                //pending
                data.memberStatus = App.i18n.get('AddMemberPending');
                data.memberPending = true;
            }else if(data.status === 1){
                //added
                data.memberStatus = App.i18n.get('AddMemberAdded');
                data.memberAdded = true;
            }else  if(data.status === 2){
                //can add
                data.memberStatus = App.i18n.get('AddMemberFailed');
                data.reAddMemberTitle = App.i18n.get('AddMemberReAdd');
                data.memberAddFailed = true;
            }
        }
        self.$el.html(Mustache.to_html(self.template, data));
        self.viewWrap = self.$el.find('.row-wrap');
        self.memberInp = self.$el.find('.member-inp');
        self.memberName = self.$el.find('.member-name');
        self.toggleIcon = self.$el.find('.toggle-icon');
        self.model.get('id') && self.$el.attr('id', App.util.getIdWithPrefix(self.model.get('id')));
		return self;
	 },
	 
	 clickRowHandler: function(e){
        var self = this;
        App.viewInstances.appView.leftMenuContextMenuView.removeSelectedItem(e.target);
        self.$el.addClass('highlight');
        return false;
	 },
	 
	 deleteMemberHandler: function(){
        var self = this,
        model = self.model;
        model.destroy({
            url: App.util.contextPath + '/project/member/'+ model.get('id')+'?projectId=' + model.get('projectId') + '&roleId=' + self.model.get('roleId'),
            success: function(){
                self.$el.remove();
                App.viewInstances.appView.MemberCollection.remove(self.model);
            	//update membercount
                var roleModel = App.viewInstances.appView.RoleCollection.get(self.model.get('roleId')),
                roleMemberCount = roleModel.get('memberCount');
                roleModel.set('memberCount', roleMemberCount - 1);
            }
        });
	 },
	 
	 keydownHandler: function(e){
        var self = this;
        if(e.which === 13){
            self.addMemberHandler();
        }
	 },
	 
	 addMemberHandler: function(){
        var self = this;
        if(self.isSaving) return false;
        var memberName = $.trim(self.memberInp.val());
        self.memberInp.val(memberName);
        if(memberName === ''){
            self.showErrorMsg('inputAccount');
            self.memberInp.focus();
            return false;
        }else if(!App.util.isGlodonAccount(memberName)){
            self.showErrorMsg('inputRightAccount');
            self.memberInp.focus();
            return false;
        }
        var memberExist = false;
        App.viewInstances.appView.MemberCollection.every(function(model){
            if(model.get('account') === memberName && self.model.get('roleId') === model.get('roleId') && self.model.get('orgId') === model.get('orgId')){
                self.showErrorMsg('inputMemberExist');
                self.memberInp.select();
                memberExist = true;
                return false;
            }
            return true;
        });
        if(memberExist) return false;
        //create member
        self.isSaving = true;
        self.showErrorMsg();
        self.model.set({
            account: memberName,
            name: memberName,
            userId: App.viewInstances.appView.leftMenuContextMenuView.getAccountIdByName(memberName),
            editingRow: false,
            status: 0,
        });
        self.viewWrap.removeClass('editing-row');
        self.model.save(null, {
            url: App.util.contextPath + '/project/member',
            error: function(){
                self.isSaving = false;
            },
            success: function(model){
            	 self.isSaving = false;
                 App.viewInstances.appView.MemberCollection.add(model);
                 self.render();
                 //update membercount
                 var roleModel = App.viewInstances.appView.RoleCollection.get(self.model.get('roleId')),
                 roleMemberCount = roleModel.get('memberCount');
                 roleModel.set('memberCount', roleMemberCount + 1);
            }
        });
        return false;
	 },
	 
	 cancelAddMemberHandler: function(){
        var self = this;
        self.$el.remove();
        self.showErrorMsg();
        return false;
	 },
     
     toggleHandler: function(e){
        var self = this;
        if(!self.model.get('org')) return false;
        self.toggleIcon.toggleClass('toggle-icon-expand');
        self.$el.find('.member-row')[self.toggleIcon.hasClass('toggle-icon-expand') ? 'show' : 'hide']();
        return false;
     },
	 
	 updateMemberName: function(){
        var self = this;
        self.memberName.text(self.model.get('name'));
	 },
	 
	 addMemberToSpecificRole: function(e){
        var self = this,
        leftMenuContextMenuView = App.viewInstances.appView.leftMenuContextMenuView;
        (new App.Collections.ItemCollection()).create({
            userId: self.model.get('userId'),
            projectId: self.model.get('projectId'),
            roleId: self.model.get('roleId'),
            org: self.model.get('org'),
            orgId: self.model.get('orgId')
        }, {
            url: App.util.contextPath + '/project/member',
            success: function(model){
                leftMenuContextMenuView.addMembersByRawData([model.toJSON()], $('#' + App.util.getIdWithPrefix(model.get('roleId'))), true);
            }
        });
        return false;
	 },
	 
	 showErrorMsg: function(msg){
        App.viewInstances.appView.leftMenuContextMenuView.roleModalErrorMsg.text(msg && App.i18n.get(msg) || '');
	 }
 });
